﻿using System;
using System.Data.Common;
using Common.Logging;
using NHibernate;
using NHibernate.Cfg;
using System.Reflection;

namespace MayfairFramework.Transaction.NHibernate
{
    public class NHibernateConnectionManager : ConnectionManager
    {
        private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        private Configuration config;
        private ISessionFactory sessionFactory;

        protected override bool isTransactionBegining(MethodInvocation mi)
        {
            throw new NotImplementedException();
        }

        #region Public Methods
        public override DbConnection getCurrentConnection(MethodInvocation mi)
        {
            throw new NotImplementedException();
        }

        public override void beginTransaction(MethodInvocation mi)
        {
            throw new NotImplementedException();
        }

        public override void commit(MethodInvocation mi)
        {
            throw new NotImplementedException();
        }

        public override void rollback(MethodInvocation mi)
        {
            throw new NotImplementedException();
        }

        public static Configuration getConfig()
        {
            NHibernateConnectionManager nhcm = (NHibernateConnectionManager)NHibernateConnectionManager.GetConnectionManager();
            return nhcm.getConfig2();
        }

        public static ISession GetCurrentSession()
        {
            NHibernateConnectionManager nhcm = (NHibernateConnectionManager)NHibernateConnectionManager.GetConnectionManager();
            return nhcm.GetSession();
        }
        #endregion

        #region Private Methods
        private Configuration getConfig2()
        {
            this.init();
            return this.config;
        }

        private void init()
        {
            lock (this)
            {
                if (this.sessionFactory == null)
                {
                    this.init2();
                }
            }
        }

        private void init2()
        {
            log.Debug("セッションファクトリーを初期化します: " + this);
            this.config = new Configuration();
            this.config.Configure();
            this.BuildSessionFactory();
        }

        private void BuildSessionFactory()
        {
            this.sessionFactory = this.config.BuildSessionFactory();
        }

        private ISession GetSession()
        {
            this.init();
            // TODO: 2010/02/06 imai とりあえず新規セッションを返却する
            return this.sessionFactory.OpenSession();
        }
        #endregion
    }
}
